package pzl.com.bluetooth;

import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import pzl.com.bluetooth.adapter.DeviceAdapter;
import pzl.com.bluetooth.constant.ConstantUtils;
import pzl.com.bluetooth.interfaces.IConnectService;
import pzl.com.bluetooth.service.ServerService;
import pzl.com.bluetooth.utils.BluetoothUtils;
import pzl.com.bluetooth.utils.Utils;

public class MainActivity extends BaseActivity implements IConnectService {
    static final String TAG = "MainActivity";

    private Button btnSwich;
    private Button btnSearch;
    private Button btnStartServer;

    private ListView lv;

    private BluetoothUtils bluetoothUtils;

    public static DeviceAdapter deviceAdapter;


    private BlueToothReceiver blueToothReceiver;

    private boolean mStarted;


    private static final int WHAT_TEXT = 1;
    private static final int WHAT_BITMAP = 2;


    //  private boolean isBluetoochDeviceEnable;

    /**
     * 服务端工作的线程池，收发数据通信线程
     */
    // private ExecutorService executorServiceWork;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        if (Build.VERSION.SDK_INT >= 23)
            requestPermissions(ConstantUtils.permissions, ConstantUtils.REQUEST_CODE_PERMISSION);

        initReceiver();
        initData();
        initView();
    }

    private void initData() {
        bluetoothUtils = BluetoothUtils.getInstance();

        // executorServiceWork = Executors.newFixedThreadPool(3);

        deviceAdapter = new DeviceAdapter(this);
        deviceAdapter.registerIConnectService(this);

    }


    private void initReceiver() {
        blueToothReceiver = new BlueToothReceiver();
        IntentFilter filter = new IntentFilter();

        filter.addAction(BluetoothDevice.ACTION_FOUND);//找到一个设备
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//搜索设备完成
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);//蓝牙设备打开或关闭状态广播
        filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);//服务端连接状态

        registerReceiver(blueToothReceiver, filter);
        registerBroadcastReceiver(new String[]{ConstantUtils.ACTION_RECEIVER_SERVERACCEPT});
    }

    private void initView() {
        btnSwich = (Button) findViewById(R.id.btnSwich);
        btnSearch = (Button) findViewById(R.id.btnSearch);
        btnStartServer = (Button) findViewById(R.id.btnStartServer);
        lv = (ListView) findViewById(R.id.lv);
        lv.setAdapter(deviceAdapter);
        setTitle(bluetoothUtils.mBluetoothAdapter.getAddress());
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public void click(View v) {
        if (!bluetoothUtils.isBluetoochDeviceEnable()) return;
        switch (v.getId()) {
            case R.id.btnSwich:
                if (bluetoothUtils.mBluetoothAdapter.isEnabled()) {//关闭蓝牙操作
                    bluetoothUtils.mBluetoothAdapter.disable();
                } else {//打开蓝牙操作
                    bluetoothUtils.mBluetoothAdapter.enable();
                }
                break;
            case R.id.btnSearch:
                if (!bluetoothUtils.mBluetoothAdapter.isEnabled()) {
                    Toast.makeText(this, "open bluetooth please ", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (bluetoothUtils.mBluetoothAdapter.isDiscovering()) {
                    styleCancelDiscovery();
                } else {
                    deviceAdapter.clearData();
                    deviceAdapter.notifyDataSetChanged();
                    styleStartDiscovery();
                }
                break;
            case R.id.btnStartServer:
                if (mStarted) return;
                btnStartServer.setEnabled(false);
                btnStartServer.setText("server started");
                btnStartServer.setTextColor(Color.parseColor("#1fe40d"));
                btnStartServer.setBackground(getResources().getDrawable(R.drawable.btn_shape2));
                mStarted = true;

                Intent intent = new Intent(this, ServerService.class);
                startService(intent);
                break;
        }


    }

    /**
     * 蓝牙打开样式
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void styleTurnOn() {
        btnSwich.setText("ON");
        btnSwich.setTextColor(Color.parseColor("#1fe40d"));
        btnSwich.setBackground(getResources().getDrawable(R.drawable.btn_shape2));
    }

    /**
     * 打开中
     */
    private void styleTurningOn() {
        btnSwich.setText("打开中...");
    }

    /**
     * 关闭中
     */
    private void styleTurningOff() {
        btnSwich.setText("关闭中...");
    }


    /**
     * 蓝牙关闭样式
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void styleTurnOff() {
        btnSwich.setText("OFF");
        btnSwich.setTextColor(Color.parseColor("#a9a9a9"));
        btnSwich.setBackground(getResources().getDrawable(R.drawable.btn_shape1));

    }


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void styleStartDiscovery() {
        btnSearch.setText("SEARCHING...");
        btnSearch.setTextColor(Color.parseColor("#1fe40d"));
        btnSearch.setBackground(getResources().getDrawable(R.drawable.btn_shape2));
        bluetoothUtils.mBluetoothAdapter.startDiscovery();
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void styleCancelDiscovery() {
        btnSearch.setText("SEARCH");
        btnSearch.setTextColor(Color.parseColor("#a9a9a9"));
        btnSearch.setBackground(getResources().getDrawable(R.drawable.btn_shape1));
        bluetoothUtils.mBluetoothAdapter.cancelDiscovery();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(blueToothReceiver);
        stopService(new Intent(this, ServerService.class));
        //executorServiceWork.shutdownNow();
    }

    @Override
    public void onConnectService(BluetoothDevice device) {
        if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
            Utils.show(this, "未配对");
            return;
        }

        bluetoothUtils.connect(device.getAddress());
        Intent intent = new Intent(this, SendActivity.class);
        intent.putExtra("serviceAddress", device.getAddress());
        startActivity(intent);
    }

    class BlueToothReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String ACTION = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(ACTION)) {
                BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                deviceAdapter.addDevice(bluetoothDevice);
                deviceAdapter.notifyDataSetChanged();
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(ACTION)) {
                Utils.show(context, "搜索完成");
                styleCancelDiscovery();
            } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(ACTION)) {
                Utils.show(context, "搜索开始");
                styleStartDiscovery();
            } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(ACTION)) {
                //Toast.makeText(MainActivity.this, "ACTION_STATE_CHANGED ", Toast.LENGTH_SHORT).show();
                int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
                int preState = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, -1);
                switch (state) {
                    case BluetoothAdapter.STATE_ON://当前蓝牙打开状态
                        styleTurnOn();
                        break;
                    case BluetoothAdapter.STATE_OFF://当前蓝牙关闭状态
                        styleTurnOff();
                        break;
                    case BluetoothAdapter.STATE_TURNING_ON://打开中
                        styleTurningOn();
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF://关闭中
                        styleTurningOff();
                        break;
                }
            } else if (BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED.equals(ACTION)) {
                int connectionState = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, -1);
                BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                switch (connectionState) {
                    case BluetoothAdapter.STATE_CONNECTED:
                        Utils.show(MainActivity.this, bluetoothDevice == null ? "" : bluetoothDevice.getName() + " 连接上了");
                        break;
                    case BluetoothAdapter.STATE_CONNECTING:
                        Utils.show(MainActivity.this, bluetoothDevice == null ? "" : bluetoothDevice.getName() + " 正在连接");
                        break;
                    case BluetoothAdapter.STATE_DISCONNECTED:
                        Utils.show(MainActivity.this, bluetoothDevice == null ? "" : bluetoothDevice.getName() + " 断开了");
                        break;
                    case BluetoothAdapter.STATE_DISCONNECTING:
                        Utils.show(MainActivity.this, bluetoothDevice == null ? "" : bluetoothDevice.getName() + " 正在断开");
                        break;
                }
            }
        }
    }

    @Override
    protected void onAcceptedNew(String clientAddress) {
        Log.d(TAG, "新的client:" + clientAddress + "连接上了");
        Intent intent = new Intent(this, SendActivity.class);
        intent.putExtra("clientAddress", clientAddress);
        startActivity(intent);
    }
}
